package proyecto.dao;

import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import proyecto.excepcion.DAOExcepcion;
import proyecto.modelo.Pelicula;

public class PeliculaDAOImpl extends HibernateDaoSupport
  implements PeliculaDAO
{
  protected Log log = LogFactory.getLog(getClass());
  private DataSource dataSource;

  public void setDataSource(DataSource dataSource)
  {
    this.dataSource = dataSource;
  }

  public Pelicula insertar(Pelicula obj) throws DAOExcepcion
  {
    try
    {
      getHibernateTemplate().save(obj);
      getHibernateTemplate().flush();
    } catch (Exception e) {
      this.log.error(e.getMessage());
      throw new DAOExcepcion(e.getMessage());
    }
    return obj;
  }

  public Pelicula obtener(int coPelicula)
    throws DAOExcepcion
  {
    this.log.info("obtener() : " + coPelicula);
    Pelicula modelo = new Pelicula();
    try {
      modelo = 
        (Pelicula)getHibernateTemplate().find(
        "from Pelicula a where trim(a.coPelicula) = ?", 
        coPelicula + "").get(0);
    } catch (Exception e) {
      this.log.error("Error: " + e.getMessage());
      throw new DAOExcepcion(e.getMessage());
    }
    return modelo;
  }

  public void eliminar(int coPelicula)
    throws DAOExcepcion
  {
    Pelicula modelo = new Pelicula();
    modelo.setCoPelicula(coPelicula);
    try {
      getHibernateTemplate().delete(modelo);
      getHibernateTemplate().flush();
    } catch (Exception e) {
      this.log.error(e.getMessage());
      throw new DAOExcepcion(e.getMessage());
    }
  }

  public Pelicula actualizar(Pelicula obj) throws DAOExcepcion
  {
    try
    {
      getHibernateTemplate().update(obj);
      getHibernateTemplate().flush();
    } catch (Exception e) {
      this.log.error(e.getMessage());
      throw new DAOExcepcion(e.getMessage());
    }
    return obj;
  }

  public List<Pelicula> listar()
    throws DAOExcepcion
  {
    this.log.info("listar()");
    List lista = new ArrayList();
    try {
      lista = getHibernateTemplate().find("from Pelicula");
    } catch (DataAccessException e) {
      this.log.error(e.toString());
      throw new DAOExcepcion(e.getMessage());
    }
    return lista;
  }
}